<?php

/**
 * LoginForm.php
 *
 * @author: antonio ramirez <antonio@clevertech.biz>
 * Date: 7/22/12
 * Time: 8:37 PM
 */
class LoginForm1 extends CFormModel {
    // maximum number of login attempts before display captcha

     public $email;
    public $password;
    public $rememberMe=false;

    /**
     * Model rules
     * @return array
     */
    public function rules() {
        return array(
            //array('username, password', 'required'),
            //array('username', 'length', 'max' => 45),
            array('password', 'length', 'max' => 50, 'min' => 6),
            //array('verifyCode', 'validateCaptcha'),
            array('password', 'authenticate'),
            array('rememberMe', 'boolean'),
            array('email', 'email'),
            array('email', 'length', 'max' => 125),
           // array('email', 'exist', 'className' => 'Customer'),
        );
    }

    /**
     * Returns attribute labels
     * @return array
     */
    public function attributeLabels() {
        return array(
            'email' => Yii::t('labels', 'E-mail'),
            'rememberMe' => Yii::t('labels', 'Remember me next time'),
        );
    }

    /**
     * Authenticates user input against DB
     * @param $attribute
     * @param $params
     */
    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            if (!$this->_identity->authenticate()) {
                if (($user = $this->user) !== null && $user->login_attempts < 100)
                    $user->saveAttributes(array('login_attempts' => $user->login_attempts + 1));
                $this->addError('username', Yii::t('errors', 'Incorrect username and/or password.'));
                $this->addError('password', Yii::t('errors', 'Incorrect username and/or password.'));
            }
        }
    }

    /**
     * Login
     * @return bool
     */
    public function login() {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->email, $this->password);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
            Yii::app()->user->login($this->_identity, $duration);
            return true;
        }
    }


}
